import pytest
import requests
import json
from unittest.mock import patch, MagicMock
import time
import random

# 配置信息
API_URL = "https://cvm.tencentcloudapi.com/"
REGION = "ap-guangzhou"
SECRET_ID = "your-secret-id"
SECRET_KEY = "your-secret-key"


def generate_signature(params, SECRET_KEY):
    """生成签名（模拟实现）"""
    return "mock-signature"


def send_request(action, params=None):
    """发送API请求（模拟实现）"""
    if params is None:
        params = {}
    common_params = {
        "Action": action,
        "Version": "2017-03-12",
        "Region": REGION,
        "SecretId": SECRET_ID,
        "Timestamp": int(time.time()),
        "Nonce": random.randint(1, 1000000),
        "SignatureMethod": "HmacSHA256"
    }
    all_params = {**common_params, **params}
    all_params["Signature"] = generate_signature(all_params, SECRET_KEY)

    response = requests.post(API_URL, data=all_params)
    return response.json()


class TestDescribeResizeOptions:
    @patch('requests.post')
    def test_success(self, mock_post):
        """测试成功查询可调整配置"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "SupportedResizeOptions": {
                    "SupportedCpuOptions": [1, 2, 4, 8],
                    "SupportedMemoryOptions": [1, 2, 4, 8, 16],
                    "SupportedCpuMemoryCombinations": [
                        {"Cpu": 1, "Memory": 1},
                        {"Cpu": 1, "Memory": 2},
                        {"Cpu": 2, "Memory": 4}
                    ]
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        result = send_request("DescribeResizeInstanceDisks")
        assert "Response" in result
        assert "SupportedResizeOptions" in result["Response"]

    @patch('requests.post')
    def test_internal_error(self, mock_post):
        """测试内部错误"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InternalError",
                    "Message": "操作内部错误"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        result = send_request("DescribeResizeInstanceDisks")
        assert result["Response"]["Error"]["Code"] == "InternalError"

    @patch('requests.post')
    def test_invalid_instance_id(self, mock_post):
        """测试无效实例ID"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidInstanceId.NotFound",
                    "Message": "实例不存在"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {"InstanceId": "invalid-id"}
        result = send_request("DescribeResizeInstanceDisks", params)
        assert result["Response"]["Error"]["Code"] == "InvalidInstanceId.NotFound"

    @patch('requests.post')
    def test_missing_instance_id(self, mock_post):
        """测试缺少实例ID"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "MissingParameter.InstanceId",
                    "Message": "缺少实例ID参数"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        result = send_request("DescribeResizeInstanceDisks", {})
        assert result["Response"]["Error"]["Code"] == "MissingParameter.InstanceId"

    @patch('requests.post')
    def test_instance_state_not_supported(self, mock_post):
        """测试实例状态不支持"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidInstanceState",
                    "Message": "实例状态不支持调整配置"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {"InstanceId": "ins-invalid-state"}
        result = send_request("DescribeResizeInstanceDisks", params)
        assert result["Response"]["Error"]["Code"] == "InvalidInstanceState"

    @patch('requests.post')
    def test_zone_not_supported(self, mock_post):
        """测试可用区不支持"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidZone.NotFound",
                    "Message": "可用区不存在或不支持"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {"Zone": "invalid-zone"}
        result = send_request("DescribeResizeInstanceDisks", params)
        assert result["Response"]["Error"]["Code"] == "InvalidZone.NotFound"

    @patch('requests.post')
    def test_unsupported_config(self, mock_post):
        """测试不支持的配置调整"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "UnsupportedOperation.ResizeConfigNotSupported",
                    "Message": "不支持的配置调整"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {"InstanceId": "ins-unsupported", "Cpu": 128, "Memory": 256}
        result = send_request("DescribeResizeInstanceDisks", params)
        assert result["Response"]["Error"]["Code"] == "UnsupportedOperation.ResizeConfigNotSupported"

    @patch('requests.post')
    def test_invalid_parameter(self, mock_post):
        """测试无效参数"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidParameter",
                    "Message": "参数格式错误"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {"InvalidParam": "invalid"}
        result = send_request("DescribeResizeInstanceDisks", params)
        assert result["Response"]["Error"]["Code"] == "InvalidParameter"

    @patch('requests.post')
    def test_permission_denied(self, mock_post):
        """测试权限不足"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "UnauthorizedOperation",
                    "Message": "无权限操作"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        result = send_request("DescribeResizeInstanceDisks")
        assert result["Response"]["Error"]["Code"] == "UnauthorizedOperation"


# 启动测试函数
def run_tests():
    pytest.main([__file__, "-v", "-s"])


if __name__ == "__main__":
    run_tests()